package cn.jeefast.rest.controller;

import cn.jeefast.common.entity.IrFeedback;
import cn.jeefast.common.utils.Code;
import cn.jeefast.common.utils.Response;
import cn.jeefast.rest.entity.TbUser;
import cn.jeefast.rest.service.IrCodeService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.swagger.annotations.*;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.jeefast.common.utils.R;
import cn.jeefast.common.validator.Assert;
import cn.jeefast.rest.annotation.AuthIgnore;
import cn.jeefast.rest.service.TbTokenService;
import cn.jeefast.rest.service.TbUserService;

import java.util.List;
import java.util.Map;

/**
 * API登录授权
 *
 * @author theodo
 * @email 36780272@qq.com
 * @date 2017-10-23 15:31
 */
@RestController
@RequestMapping("/api/")
@Api(tags ="用户个人相关接口")
@CrossOrigin
public class ApiLoginController {
    @Autowired
    private TbUserService userService;
    @Autowired
    private TbTokenService tokenService;
    @Autowired
    private IrCodeService codeService;

    /**
     * 账号密码登录
     */
    @AuthIgnore
    @PostMapping("login")
    @ApiOperation(value="账号密码登录", notes="登录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "mobile", value = "登录手机号", required = true, dataType="String",paramType="query"),
        @ApiImplicitParam(name = "password", value = "如果使用密码登录，则code不传", required = false, dataType="String",paramType="query"),
        @ApiImplicitParam(name = "code", value = "如果使用验证码登录，则password不传", required = false, dataType="String",paramType="query")
})
    public R login(String mobile, String password, String code){
        Assert.isBlank(mobile, "手机号不能为空");

        long userId;

        if(password!=null){
            //使用账号密码登录
            userId = userService.login(mobile, password);
        }else{
            //验证手机号和验证码是否匹配
            R r = codeService.checkCode(mobile, code);
            if((Integer)r.get("code")!=0){
                return r;
            }
            //根据手机号查询用户ID
            EntityWrapper<TbUser> ew = new EntityWrapper<>();
            ew.eq("mobile",mobile);
            List<TbUser> tbUsers = userService.selectList(ew);
            if(tbUsers==null){
                return R.error("找不到用户").put("data",null);
            }
            userId = tbUsers.get(0).getUserId();
        }

        //生成token
        Map<String, Object> map = tokenService.createToken(userId);

        return R.ok("登录成功").put("data",map);
    }



}
